<template>
  <div class="relative page-container give-car-wrapper">
    <page-form :model="form" layout="vertical" :rules="rules" ref="formRef">
      <div class="page-form-block">
        <!-- 统计 -->
        <summary-info :summaryList="summaryLease" />
        <a-divider />
        <summary-info :summaryList="summaryMember">
          <template #memberName>
            <div class="flex">
              {{ memberInfo?.memberName || '-' }}
              <page-form-item
                label=""
                :span="4"
                field="driverFile"
                style="margin-left: 10px"
                v-if="orderDetailGetted && (!memberInfo.driverFrontFileId || !memberInfo.driverReverseFileId)"
              >
                <a-button size="mini" type="primary" @click="uploadDrivierFn"> 未上传驾驶证 </a-button>
              </page-form-item>
              <page-form-item
                label=""
                :span="4"
                field="idCardFile"
                style="margin-left: 10px"
                v-if="orderDetailGetted && (!memberInfo.idCardFrontFileId || (memberInfo.cardType == 0 && !memberInfo.idCardReverseFileId))"
              >
                <a-button size="mini" type="primary" @click="uploadIdCardFn"> 未上传身份证明 </a-button>
              </page-form-item>
            </div>
          </template>
        </summary-info>
      </div>
      <a-divider />

      <card title="交车信息" style="margin-top: 20px">
        <box-info :carId="orderInfo.carId" style="margin-bottom: 20px" />
        <page-form-row>
          <page-form-item label="交车里程" field="startCarMileage">
            <i-input-number :precision="0" unit="公里" v-model="form.startCarMileage" />
          </page-form-item>
          <page-form-item label="交车油(电)量" field="startCarOil">
            <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.startCarOil" />
          </page-form-item>
          <page-form-item field="giveStaffId" label="交车人">
            <remote-select
              v-model="form.giveStaffId"
              :params="{
                oldId: defaultStaffId ? defaultStaffId : undefined,
                siteIdList: [orderInfo.siteId],
              }"
              type="staff_authOrg"
            />
          </page-form-item>
          <page-form-item field="useStartTime" label="交车时间">
            <i-date-picker class="w-full" v-model="form.useStartTime" showTime />
          </page-form-item>
          <page-form-item label="交车备注" size="2/3">
            <i-textarea v-model="form.useStartRemark" />
          </page-form-item>
          <!-- 针对自动维护的铁行渠道订单的修改 -->
          <page-form-item field="giveMilesFileId" label="交车里程照片/油(电)量照片" size="1">
            <upload-img v-model="form.giveMilesFileId" :limit="1" />
          </page-form-item>
          <page-form-item field="fileIds" label="交车照片" size="1">
            <upload-img v-model="form.fileIds" />
          </page-form-item>
          <page-form-item label="交车视频" size="1" class="mb-0">
            <upload-video v-model="form.giveVideoFileIds" :max="1" />
          </page-form-item>
        </page-form-row>
      </card>
    </page-form>
    <!-- 费用信息 -->
    <div class="relative fee-pane-content">
      <page-form :model="feeForm" ref="feeFormRef" layout="vertical">
        <card toggle :toggleDefault="false" :showDivider="false">
          <template #title>交车费</template>
          <div class="mb-4" v-if="orderInfo?.channelType == -3 && orderInfo?.channelOrderMaintenance == 1">
            <a-alert>如需添加线上费用，请先前往铁行平台进行添加，完成添加后，会自动同步至启程平台的此订单中。</a-alert>
          </div>
          <template v-for="(item, index) in feeForm.orderFee" :key="index">
            <fee-pane
              :orderFeeIndex="index"
              :disabledOnlineFee="orderInfo.orderSource == 1 || (orderInfo?.channelType == -3 && orderInfo?.channelOrderMaintenance == 1)"
            />
          </template>
        </card>
      </page-form>
    </div>
  </div>
  <!-- 底部 footer -->
  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
  <!-- 上传驾驶证照片 -->
  <upload-driver-license-modal ref="uploadDriverLicenseModalRef" frontTitle="证件正页" backTitle="证件副页" @ok="uploadSuccessFn" />

  <!-- 上传身份证明照片 -->
  <upload-id-card-modal ref="uploadIdCardModalRef" @ok="uploadIdCardSuccessFn" />
</template>
<script setup name="ShortOrderGiveCar">
  import { ref, provide, computed, reactive } from 'vue'
  import { useRoute } from 'vue-router'
  import { Modal } from '@arco-design/web-vue'
  import { getShortOrdrDetails, giveCar } from '@/api/order/sOrder'
  import feePane from './components/order-fee/fee-pane.vue'
  import { buildCostInfoParam, initFeeDetail, getStoreTemplateDetail } from './components/order-fee/fee-utils.js'
  import uploadDriverLicenseModal from './components/upload-driver-license-modal.vue'
  import uploadIdCardModal from './components/upload-id-card-modal.vue'
  import iTextarea from '@/views/order/short-order/components/i-textarea.vue'
  import summaryInfo from './components/summary-info.vue'
  import boxInfo from '../../business/workOrder/order/components/box-modal.vue'
  import useNavigate from '@/hooks/useNavigate'
  import { orderIsTiexing } from './utils.js'
  // 订单拦截hooks
  import useOrderIntercept from './hooks/useTieXingInterceptor'
  const { navigateBack } = useNavigate()
  import dayjs from 'dayjs'
  import useUserStore from '@/store/modules/user'
  const userStore = useUserStore()
  const route = useRoute()
  const orderId = route.params.id
  const orderInfo = ref({})
  const memberInfo = ref({})
  const orderDetailGetted = ref(false)

  const form = ref({
    id: orderId,
    useStartTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  })
  // 处理默认值
  const rules = reactive({
    giveStaffId: [{ required: true, message: '请选择交车人' }],
    useStartTime: [{ required: true, message: '请选择交车时间' }],
    startCarMileage: [{ required: true, message: '请输入交车里程' }], // 交车里程
    startCarOil: [{ required: true, message: '请输入交车油(电)量' }], // 交车油(电)量
  })
  const formRef = ref()
  provide('form', form)

  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      [
        {
          label: '预计租赁周期',
          value: `${orderInfoVal.startTime} - ${orderInfoVal.endTime}`,
        },
        { label: '租期', value: orderInfoVal.rentDays },
        { label: '订单来源', value: orderInfoVal.orderSourceName },
      ],
      [
        { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
        { label: '车型', value: orderInfoVal.originalModelName },
        { label: '交车车型', value: orderInfoVal.carModelName },
      ],
      [{ label: '交车车牌号', value: orderInfoVal.carLicenseNo }],
    ]
  })

  const summaryMember = computed(() => {
    const memberInfoVal = memberInfo.value
    const orderInfoVal = orderInfo.value
    return [
      orderInfoVal.clientId
        ? [
            { label: '承租人', slotName: 'memberName' },
            { label: '企业名称', value: orderInfoVal.clientName },
            { label: '证件类型', value: memberInfoVal?.cardTypeName },
          ]
        : [
            { label: '承租人', slotName: 'memberName' },
            { label: '证件类型', value: memberInfoVal?.cardTypeName },
          ],
      [
        { label: '联系电话', value: memberInfoVal?.phone },
        { label: '证件号', value: memberInfoVal?.cardNumber },
      ],
    ]
  })

  const priceTemplateId = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['addServiceFee', 'preferentialFee', 'otherFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  const defaultStaffId = ref()
  if (orderId) {
    getShortOrdrDetails({ id: orderId }).then((res) => {
      orderDetailGetted.value = true
      const result = res.result
      orderInfo.value = result.orderInfo
      memberInfo.value = result.memberInfoDto
      // 处理默认值
      // 车务专员 | 当前登录者 id
      defaultStaffId.value = orderInfo.value.giveStaffId || userStore.employeeId
      // 默认交车人
      form.value.giveStaffId = defaultStaffId.value
      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 1, (storeTemplate, templateId) => {
        let feeValue = feeForm.value
        initFeeDetail(feeValue, storeTemplate)
        // 更新费用模板 id
        priceTemplateId.value = templateId
      })
      // 自动维护的铁行渠道订单逻辑处理
      updateTiexingStore()
    })
  }
  const updateTiexingStore = () => {
    // 针对自动维护的铁行渠道订单，将交车照片字段变为必填项
    if (orderIsTiexing(orderInfo.value)) {
      Object.assign(rules, {
        fileIds: [{ required: true, message: '请上传交车照片' }],
        giveMilesFileId: [{ required: true, message: '请上传交车里程照片' }],
        driverFile: [
          {
            required: true,
            validator: (value, callback) => {
              if (orderDetailGetted.value && (!memberInfo.value.driverFrontFileId || !memberInfo.value.driverReverseFileId)) {
                return callback('请完善驾驶证')
              }
              callback()
            },
          },
        ],
        idCardFile: [
          {
            required: true,
            validator: (value, callback) => {
              if (
                orderDetailGetted.value &&
                (!memberInfo.value.idCardFrontFileId || (memberInfo.value.cardType == 0 && !memberInfo.value.idCardReverseFileId))
              ) {
                return callback('请完善身份证')
              }
              callback()
            },
          },
        ],
      })
    }
  }
  // 上传驾驶证
  const uploadDriverLicenseModalRef = ref()
  const uploadDrivierFn = () => {
    uploadDriverLicenseModalRef.value.open(memberInfo.value.id, memberInfo.value.driverFrontFileId, memberInfo.value.driverReverseFileId)
  }
  // 上传完成
  // 更新驾驶证正反面信息
  const uploadSuccessFn = (info) => {
    memberInfo.value.driverFrontFileId = info.driverFrontFileId
    memberInfo.value.driverReverseFileId = info.driverReverseFileId
  }
  // 上传身份证明
  const uploadIdCardModalRef = ref()
  const uploadIdCardFn = () => {
    uploadIdCardModalRef.value.open(
      memberInfo.value.id,
      memberInfo.value.cardType,
      memberInfo.value.idCardFrontFileId,
      memberInfo.value.idCardReverseFileId
    )
  }
  // 上传完成
  // 更新身份证明正反面信息
  const uploadIdCardSuccessFn = (info) => {
    memberInfo.value.idCardFrontFileId = info.idCardFrontFileId
    memberInfo.value.idCardReverseFileId = info.idCardReverseFileId
  }
  const okLoading = ref(false)
  // 校验应收未收的租车押金
  // 提示：如果存在应收未收的租车押金，则需要提示用户确认交车
  const checkUnReceiveRentalDeposit = () => {
    return new Promise((resolve) => {
      // 存在应收未收的订单租金
      if (orderInfo.value.carDepositStatus == 10) {
        Modal.confirm({
          title: '提示',
          content: `该笔订单存在应收未收的租车押金${orderInfo.value.carDeposit}元，是否确认交车？`,
          okText: '确认交车',
          onOk: () => {
            resolve()
          },
        })
      } else {
        resolve()
      }
    })
  }
  const submitFn = (noticeSuccess) => {
    formRef.value.validate((error) => {
      if (!error) {
        checkUnReceiveRentalDeposit().then(() => {
          okLoading.value = true
          let feeFormValue = feeForm.value
          let costInfo = buildCostInfoParam(feeFormValue)
          const param = {
            ...form.value,
            orderFee: costInfo.orderFee[0],
          }
          giveCar(param)
            .then(({ result }) => {
              // 调用铁行接口失败：false
              if (result && result.success == false) {
                return useOrderIntercept(orderInfo.value, 'giveCarSubmit', () => {
                  navigateBack()
                })
              }
              noticeSuccess()
              navigateBack()
            })
            .finally(() => (okLoading.value = false))
        })
      }
    })
  }
</script>
<style lang="less" scoped></style>
